package com.fhminyi.dao;

import com.fhminyi.model.Category;
import com.fhminyi.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CategoryDao {
    // 获取所有分类
    public List<Category> getAllCategories() throws SQLException {
        List<Category> categories = new ArrayList<>();
        String sql = "SELECT * FROM 分类";
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                Category category = new Category();
                category.setCategoryId(rs.getInt("分类_id"));
                category.setCategoryName(rs.getString("分类名称"));
                categories.add(category);
            }
        }
        return categories;
    }

    // 根据分类ID获取分类
    public Category getCategoryById(int categoryId) throws SQLException {
        String sql = "SELECT * FROM 分类 WHERE 分类_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, categoryId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    Category category = new Category();
                    category.setCategoryId(rs.getInt("分类_id"));
                    category.setCategoryName(rs.getString("分类名称"));
                    return category;
                }
            }
        }
        return null;
    }

    // 添加分类
    public void addCategory(Category category) throws SQLException {
        String sql = "INSERT INTO 分类 (分类名称) VALUES (?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, category.getCategoryName());
            pstmt.executeUpdate();
        }
    }

    // 更新分类
    public void updateCategory(Category category) throws SQLException {
        String sql = "UPDATE 分类 SET 分类名称 = ? WHERE 分类_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, category.getCategoryName());
            pstmt.setInt(2, category.getCategoryId());
            pstmt.executeUpdate();
        }
    }

    // 删除分类
    public void deleteCategory(int categoryId) throws SQLException {
        String sql = "DELETE FROM 分类 WHERE 分类_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, categoryId);
            pstmt.executeUpdate();
        }
    }
}